package com.lecture.java8.zip;

import java.io.*;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;

/**
 * @author luyn
 * @version 1.0
 * @description
 * @date 2020/7/23 10:43
 */
public class ZipUtil2 {
    private static final int  BUFFER_SIZE = 2 * 1024;

    public static void toZip(List<File> srcFiles , OutputStream out)throws Exception {
        long start = System.currentTimeMillis();
        ZipOutputStream zos = null ;
        try {
            zos = new ZipOutputStream(out);
            for (File srcFile : srcFiles) {
                byte[] buf = new byte[BUFFER_SIZE];
                zos.putNextEntry(new ZipEntry(srcFile.getName()));
                int len;
                FileInputStream in = new FileInputStream(srcFile);
                while ((len = in.read(buf)) != -1){
                    zos.write(buf, 0, len);
                }
                zos.closeEntry();
                in.close();
            }
            long end = System.currentTimeMillis();
            System.out.println("压缩完成，耗时：" + (end - start) +" ms");
        } catch (Exception e) {
            throw new RuntimeException("zip error from ZipUtils",e);
        }finally{
            if(zos != null){
                try {
                    zos.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) throws Exception {
        File file1 = new File("c:\\1.txt");
        File file2 = new File("c:\\2.txt");
        List<File> files = new ArrayList<File>();
        files.add(file1);
        files.add(file2);
        OutputStream out = new FileOutputStream("c:\\1.zip");
        ZipUtil2.toZip(files,out);
    }

}
